package me.zhengjie.modules.pay.wechat.sdk;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.hires.domain.Hires;
import me.zhengjie.modules.hires.domain.vo.PublishHiresVo;
import me.zhengjie.modules.hires.service.HiresService;
import me.zhengjie.modules.hires.service.dto.HiresDto;
import me.zhengjie.modules.hires.service.mapstruct.HiresMapper;
import me.zhengjie.modules.order.domain.WechatOrder;
import me.zhengjie.modules.order.service.WechatOrderService;
import me.zhengjie.modules.order.service.dto.WechatOrderDto;
import me.zhengjie.modules.order.service.mapstruct.WechatOrderMapper;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.enums.PayTypeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@RequestMapping("/api/pay/wechat")
@RestController
@Api("微信支付接口")
@AllArgsConstructor
public class WechatPay {

    private final WxPayService wxPayService;

    private final WechatOrderService wechatOrderService;
    private final WechatOrderMapper wechatOrderMapper;
    private final HiresService hiresService;
    private final HiresMapper hiresMapper;


    @ApiOperation(value = "支付回调通知处理")
    @RequestMapping("/notify/order")
    public String parseOrderNotifyResult(@RequestBody String xmlData) {
        final WxPayOrderNotifyResult notifyResult;
        try {
            notifyResult = wxPayService.parseOrderNotifyResult(xmlData);

            String attach = notifyResult.getAttach();
            PayTypeEnum byType = PayTypeEnum.getByType(attach);
            if (Objects.isNull(byType)) {
                return WxPayNotifyResponse.fail("attach 参数异常");
            }
            notifyResult.getTransactionId(); //微信支付订单号
            String outTradeNo = notifyResult.getOutTradeNo();// 商户订单号
            // TODO 根据自己业务场景需要构造返回对象  拿到订单号  更新订单信息
            WechatOrder wechatOrder = wechatOrderMapper.toEntity(wechatOrderService.findById(outTradeNo));
            wechatOrder.setTransactionId(notifyResult.getTransactionId());
            wechatOrder.setEndTime(notifyResult.getTimeEnd());
            wechatOrder.setStatus(1);
            wechatOrderService.update(wechatOrder);

            switch (byType){
                case HIRES:
                    Hires hires = hiresMapper.toEntity(hiresService.findById(wechatOrder.getAttachId()));
                    hires.setStatus(0);
                    hiresService.update(hires);
            }

        } catch (WxPayException e) {
            e.printStackTrace();
            log.error(e.getCustomErrorMsg(), e);
            return WxPayNotifyResponse.fail("处理失败");
        }
        return WxPayNotifyResponse.fail("处理失败");
    }










    @RequestMapping(value = "test")
    @ResponseBody
    @ApiOperation("生成支付订单")
    public <T> T order(HttpServletRequest req) {
//        SecurityUtils.getCurrentUsername();
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setBody("测试支付");
        request.setOutTradeNo("" + System.currentTimeMillis());
        request.setAttach(PayTypeEnum.HIRES.getType());
        request.setTotalFee(1);
        request.setTradeType(WxPayTradeTypeEnum.JSAPI.getTradeType());
        request.setSpbillCreateIp(StringUtils.getIp(req));
        request.setNotifyUrl("https://test.com/");
        request.setOpenid("oPIWw4obZ3UL6MWj8Kgq3f_dlj4I");
        try {
            return wxPayService.createOrder(request);
        } catch (WxPayException e) {
            e.printStackTrace();
            log.error(e.getCustomErrorMsg(), e);
            throw new BadRequestException(StringUtils.isNotEmpty(e.getCustomErrorMsg()) ? e.getCustomErrorMsg() : StringUtils.isNotEmpty(e.getReturnMsg()) && !e.getReturnMsg().equals("OK") ? e.getReturnMsg() : e.getErrCodeDes());
        }
    }



}
